package com.shop.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shop.constan.Login;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.domain.SysUser;
import com.shop.mapper.SysUserMapper;
import com.shop.service.SysUserService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService, UserDetailsService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        //2.查询用户
        //3.判断前台用户还是后台
        //4.判断菜单
        //1.拿到请求头
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String header = request.getHeader(Login.LOGIN_TYPE);
        //判断前台还是后台
        if (StringUtils.isEmpty(header)) {

          return null;

        }
        if (Login.SYS_LOGIN.contains("sys_user")) {
            //查后台user表
            SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, s));
            if (!ObjectUtil.isEmpty(sysUser)) {
                //查权限
                List<String> auths = sysUserMapper.queryAuth(sysUser.getUserId());
                if (!CollectionUtils.isEmpty(auths)) {
                    //设置进去
                    sysUser.setAuths(auths);
                }
                return sysUser;
            }

        } else if (Login.MEMBER.contains("members")) {
            return null;
        } else {
            return null;
        }
    return null;
    }
}
